import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import { stat } from 'fs'

declare var $: any
declare var echarts: any
@Component({
  selector: 'sa-service-charge-bill',
  templateUrl: './service-charge-bill.component.html'
})
export class ServiceChargeBillComponent implements OnInit {
  tableData: any = [] //table数据
  statusList: any = ['未结算', '未结清', '已结清'] // 结算状态
  startTime: string = '' //开始时间
  endTime: string = '' //结束时间
  selectedCompanyId: string = '' //公司ID
  selectedCompanyName: string = '' //公司名称
  carNumber: string = ''
  dataSort: string = '1'
  sortBy: string = '0'
  sortType: string = '1'
  status: string = ''
  userName: string = '' //上传人

  searchCarParam: any = {
    month: '',
    accountType: 1,
    billType: '1',
    status: ''
  } // 搜索参数

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      //			this.curPage = queryParams.nowPage == undefined? 1:queryParams.nowPage;
      const year = new Date().getFullYear()
      let month = new Date().getMonth() + 1
      let day = new Date().getDate()
      this.searchCarParam.month = `${year}-${month < 10 ? '0' + month : month}`
    })
  }
  ngOnInit() {
    this.initCompanySelect()
    this.initDate().then(() => {
      this.load()
    })
  }
  ngOnDestroy() {
    document.onclick = null
  }

  //   选择月份函数
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#startTimePicker')
            .datetimepicker({
              //时间插件
              format: 'yyyy-mm',
              language: 'zh-CN',
              weekStart: 1,
              autoclose: 1,
              startView: 'year',
              maxView: 'decade',
              minView: 'year',
              forceParse: false,
              pickerPosition: 'bottom-left'
            })
            .on('changeDate', function (e) {
              var date = e.date
              var year = date.getFullYear()
              var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
              that.searchCarParam.month = `${year}-${month}`
            })
          resolve(true)
        })
      })
    })
  }
  //清除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker1').val('').change()
    $('#datetimepicker2').val('').change()
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }
  // 排序change
  sortChange() {
    switch (this.dataSort) {
      case '1':
        this.sortBy = '0'
        this.sortType = '1'
        break
      case '2':
        this.sortBy = '0'
        this.sortType = '0'
        break
      case '3':
        this.sortBy = '1'
        this.sortType = '1'
        break
      case '4':
        this.sortBy = '1'
        this.sortType = '0'
        break
      case '5':
        this.sortBy = '2'
        this.sortType = '1'
        break
      case '6':
        this.sortBy = '2'
        this.sortType = '0'
        break
      default:
        this.sortBy = '0'
        this.sortType = '1'
        this.dataSort = '1'
        break
    }
  }
  //表格搜索
  table_search() {
    this.load()
  }
  //刷新
  refresh() {
    this.load()
  }
  //初始化加载list数据
  load() {
    this.jsonApiService
      .http_obj('ChargeCorporAccount/listTree.html', {
        data: JSON.stringify(this.searchCarParam)
      })
      .subscribe(data => {
        // if (data.success) {
        if (data.success) {
          var result = data.data
          // 遍历处理子节点
          this.tlist = []
          const newData = this.redirectResultData(result, {}, [])
          this.initTableData(newData)
          this.tableData = this.tlist
        }
      })
  }
  // 标记等级的
  level = 0
  // 最后遍历形成的平级数组
  tlist = []
  // 父级的id
  parentId: string | number = ''

  // 递归处理表单数据
  initTableData(result) {
    for (let index = 0; index < result.length; index++) {
      const item = result[index]
      item.noShow = false
      this.tlist.push(item)
      if (item.isTop) {
        // this.level = 0
        item.parentId = 0
      } else {
        // item.parentId = this.parentId
      }
      // item.level = this.level
      // 这里是个数组
      if (item.childNode && item.childNode.length > 0) {
        // this.parentId = item.id
        item.isShowChild = true
        // this.level += 1
        this.initTableData(item.childNode)
      }
    }
  }

  // 重构数据
  redirectResultData = (data: any, obj: any = {}, arr: any = []) => {
    let syArr: any = []
    data.forEach(item => {
      const currentId = item.id
      const parentId = item.parent
      obj[currentId] = item
      obj[currentId].noShow = false
      obj[currentId].parentId = parentId ? parentId : '0'
      if (!parentId) {
        // 最顶级
        obj[currentId].level = 0
        obj[currentId].isTop = true
        arr.push(obj[currentId])
      } else {
        if (obj[parentId]) {
          if (obj[parentId].isTop || obj[parentId].level) {
            obj[currentId].isShowChild = true
            // 找到父集
            obj[currentId].level = obj[parentId].level + 1
            if (obj[parentId].childNode) {
              obj[parentId].childNode.push(obj[currentId])
            } else {
              obj[parentId].childNode = [obj[currentId]]
            }
          } else {
            syArr.push(obj[currentId])
          }
        } else {
          // 找不到父集
          syArr.push(obj[currentId])
        }
      }
    })
    if (syArr.length > 0) {
      arr = this.redirectResultData(syArr, obj, arr)
    }
    return arr
  }
  // 删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('projectDaily/deletedById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }
  // 编辑表单数据
  projectDailyFrom: any = {}
  itemPageForm: any = {
    title: '代维人员',
    key: 'maintenanceStaff'
  }
  //公司选中回调
  companySelected(data) {
    this.selectedCompanyId = data.companyId
    this.selectedCompanyName = data.companyName
  }
  editItemPage(type, name, row) {}

  jumpPageAccount(Url, row) {
    const _time = this.searchCarParam.month ? this.searchCarParam.month.split('-') : ''
    let startTime = ''
    let endTime = ''
    if (_time) {
      startTime = `${_time[0]}-${_time[1]}-01 00:00:00`
      const totalDay = new Date(_time[0], _time[1], 0).getDate()
      endTime = `${_time[0]}-${_time[1]}-${totalDay} 23:59:59`
    }
    const rowobj = {
      companyId: row.id,
      companyName: row.text,
      billType: '1',
      startTime,
      endTime
    }
    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('jumpTo' + Url, JSON.stringify(rowobj))
    window.open(BaseURL + '#' + Url)
  }

  // 页面跳转
  jumpPage(Url, row, status) {
    const _time = this.searchCarParam.month ? this.searchCarParam.month.split('-') : ''
    let startTime = ''
    let endTime = ''
    if (_time) {
      startTime = `${_time[0]}-${_time[1]}-01 00:00:00`
      const totalDay = new Date(_time[0], _time[1], 0).getDate()
      endTime = `${_time[0]}-${_time[1]}-${totalDay} 23:59:59`
    }
    let rowobj = {}
    if (!row.parent) {
      rowobj = {
        companyId: row.id,
        companyName: row.text,
        status: status,
        billType: '1',
        startTime,
        endTime
      }
    } else {
      rowobj = {
        companyId: row.parent,
        companyName: row.parentName,
        factoryId: row.id,
        factoryName: row.text,
        status: status,
        billType: '1',
        startTime,
        endTime
      }
    }

    let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port
    common.setCookie('jumpTo' + Url, JSON.stringify(rowobj))
    window.open(BaseURL + '#' + Url)
  }
  // 展开单行
  openTr(parent) {
    parent.isShowChild = !parent.isShowChild
    for (let index = 0; index < this.tableData.length; index++) {
      const element = this.tableData[index]
      // 不仅id要一样  date也要一样
      if (element.parentId == parent.id) {
        // noShow 不展示 所以要和父组件的isShowChild取反
        element.noShow = !parent.isShowChild
        // 为了适配多级
        if (element.childNode && element.childNode.length > 0) {
          this.shrinkData(element.childNode, !parent.isShowChild)
        }
      }
    }
    // console.log(this.tableData, "this.tableData");
  }
  // 递归进行收缩或展开  适配多级
  shrinkData(data, state) {
    for (let idx = 0; idx < data.length; idx++) {
      const element = data[idx]
      // 只更改子集的
      if (!element.isTop) {
        element.noShow = state
      }
      if (element.childNode && element.childNode.length != 0) {
        element.isShowChild = !state
        this.shrinkData(element.childNode, state)
      }
    }
  }

  isAllOpen: boolean = true
  btnText: string = '一键收缩'
  // 一键展开一键缩放
  oneKeyChange() {
    if (this.isAllOpen) {
      this.shrinkData(this.tableData, true)
      this.isAllOpen = false
      this.btnText = '一键展开'
    } else {
      this.shrinkData(this.tableData, false)
      this.isAllOpen = true
      this.btnText = '一键收缩'
    }
  }

  del_accountSelect() {
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#accountSelect').val('')
    this.searchCarParam.accountName = ''
    this.searchCarParam.accountId = ''
    $('#select2-accountSelect-container').empty()
    $('#select2-accountSelect-container').attr('title', '')
    $('#select2-accountSelect-container').prepend(str)
  }

  //select2 格式回调函数
  formatRepo(state) {
    if (!state.id) {
      return state.text
    }
    var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>')
    return $state
  }

  //拉取api数据
  initAcountSelect(companyName) {
    var that = this
    that.jsonApiService
      .http_obj('CorporAccount/list.html', {
        data: JSON.stringify({
          companyName
        })
      })
      .subscribe(data => {
        if (data.success) {
          var apiList = data.data
          var selectdata = []
          for (var i = 0; i < apiList.length; i++) {
            var obj = {
              id: apiList[i].id,
              text: apiList[i].accountName
            }
            selectdata[i] = obj
          }
        }
        this.initSelected(selectdata, '#accountSelect', data => {
          that.searchCarParam.accountName = data.text
          that.searchCarParam.accountId = data.id
        })
      })
  }

  // 初始化账户名称
  initSelected(selectdata, id, callback = null) {
    var that = this
    System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
      System.import('assets/js/select2-zh-CN.js').then(() => {
        $(id).html('')
        $(id)
          .select2({
            language: 'zh-CN',
            placeholder: '请选择',
            allowClear: true,
            data: selectdata, //为Select添加数据
            templateResult: this.formatRepo
          })
          .on('select2:select', function (e) {
            var data = e.params.data
            callback && callback(data)
          })
        var option = new Option('', '', true, true)
        $(id).append(option)
      })
    })
  }

  //拉取项目名称api数据
  initCompanySelect() {
    var that = this
    that.jsonApiService
      .http_obj('CorporAccount/list.html', {
        data: JSON.stringify({
          searchKey: ''
        })
      })
      .subscribe(data => {
        if (data.success) {
          var apiList = data.data
          var selectdata = []
          for (var i = 0; i < apiList.length; i++) {
            var obj = {
              id: apiList[i].companyId,
              text: apiList[i].companyName
            }
            selectdata[i] = obj
          }
        }
        this.initSelected(selectdata, '#companySelect', data => {
          this.searchCarParam.companyName = data.text
          this.searchCarParam.companyId = data.id
          that.searchCarParam.accountName = ''
          that.searchCarParam.accountId = ''
          that.initAcountSelect(data.text)
        })
      })
  }

  del_companySelect() {
    var str = $("<span class='select2-selection__placeholder'>请选择</span>")
    $('#companySelect').val('')
    this.searchCarParam.companyName = ''
    this.searchCarParam.companyId = ''
    $('#select2-companySelect-container').empty()
    $('#select2-companySelect-container').attr('title', '')
    $('#select2-companySelect-container').prepend(str)
  }
}
